#!/bin/sh
# Helper script to bootstrap comun from self hosted code, at this point using.
# You can choose the backend with parameter (C is used by default). Beware:
# python is incredibly slow.

BACKEND="${1:-c}"
BOOTSTRAPDIR="bootstrap"

echo "bootstrapping comun with $BACKEND backend"

# cmbFile outputFile
compileBytecode ()
{
  echo "compiling bytecode: $1 to $2"

  if [ $BACKEND = "c" ]; then
    cat $1 | ./backend > $1.c
    cc -O3 -o $2 $1.c
  else # python
    cat $1 | ./backend > $2
  fi

  chmod +x $2
}

# cmnFile outputFile
compileCode ()
{
  echo "compiling code: $1 to $2"
  cat $1 | ./comun_minicompiler > $1.cmb
  compileBytecode $1.cmb $2
}

rm -rf $BOOTSTRAPDIR
mkdir $BOOTSTRAPDIR
cd $BOOTSTRAPDIR

if [ $BACKEND = "c" ]; then
  cc -O3 -o ./backend ../backends/c.c
elif [ $BACKEND = "python" ]; then
  cp ../backends/python.py ./backend
else
  echo "unknown backend: $BACKEND"
  exit 1
fi

compileBytecode ../../other/comun_minicompiler.cmb comun_minicompiler
compileCode ../comun_includeproc.cmn comun_includeproc

echo "merging sources for full comun"

cd ..

./includeproc.sh $BOOTSTRAPDIR/comun_includeproc comun.cmn cmn_all.cmn \
  cmn_bytecode.cmn cmn_bytecode_extra.cmn cmn_compiler.cmn cmn_general.cmn \
  cmn_interpreter.cmn cmn_tokenizer.cmn \
  cmn_optimizer.cmn > $BOOTSTRAPDIR/comun_merged.cmn

cd $BOOTSTRAPDIR

compileCode comun_merged.cmn comun_tmp

echo "compiling comun second time (optimizations)"
cat comun_merged.cmn | ./comun_tmp -co > comun.cmb

compileBytecode comun.cmb comun

echo "DONE"
